package com.zw.mes.module.technology.service;

import com.zw.mes.entity.technology.Result;
import com.zw.mes.module.system.service.LogService;
import com.zw.mes.module.technology.mapper.PurchasedMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.*;

import static com.zw.mes.util.BeanUtil.getNullPropertyNames;


/**
 * @author mayongfeng
 * @version 1.0.0
 * @ClassName PurchasedService.java
 * @Description TODO
 * @createTime 2021年01月29日 09:13:00
 */
@Service
@SuppressWarnings("all")
public class PurchasedService {

    @Autowired
    private PurchasedMapper purchasedMapper;
    @Autowired
    private LogService logService;


    public Result getSumNum(Result result) {
        int sumNum = 0;
        /** 查询提报计划为：部长审核过，外购件，非成本中心 主表加个拆分状态*/
        List<Result> withMakeReportQuery = purchasedMapper.findWithMakeReportQuery(result);
        Set<String> proList = new HashSet<>();

        /** 循环查询出原始单和变更单的计划条数*/
        for (Result result1 : withMakeReportQuery) {
            if(result1.getLssueStatus()==1){
                proList.add(result1.getProCode());
            }
            //原始单
            if(result1.getSheetType()==1 && result1.getLssueStatus()==1){
                int countNum = purchasedMapper.findSelectPlanNum(result1.getId());
                result1.setUnplanNum(countNum);
                sumNum += countNum;
                //变更单
            }else if(result1.getSheetType()==2 && result1.getLssueStatus()==1) {
                int countChangeNum = purchasedMapper.findSelectChangePlanNum(result1.getId());
                result1.setUnplanNum(countChangeNum);
                sumNum += countChangeNum;
            }

        }
        result.setUnplanNum(sumNum);
        result.setUnproNum(proList.size());
        return result;


    }



    public List<Result> findWithReportQuery(Result result) {
        int sumNum = 0;
        /** 查询提报计划为：部长审核过，外购件，非成本中心 主表加个拆分状态*/
        List<Result> withMakeReportQuery = purchasedMapper.findWithMakeReportQuery(result);

        /** 循环查询出原始单和变更单的计划条数*/
        for (Result result1 : withMakeReportQuery) {
            //原始单
            if(result1.getSheetType()==1){
                int countNum = purchasedMapper.findSelectPlanNum(result1.getId());
                result1.setUnplanNum(countNum);
                sumNum += countNum;
                //变更单
            }else if(result1.getSheetType()==2) {
                int countChangeNum = purchasedMapper.findSelectChangePlanNum(result1.getId());
                result1.setUnplanNum(countChangeNum);
                sumNum += countChangeNum;
            }

        }

        return withMakeReportQuery;
    }
    /**
     * @Author mayongfeng
     * @Date 10:17 2021/2/20
     * @Description 通过Id查询该项目下的表头
     *
     **/
    public List<Result> getSelectById(Integer id) {
        List<Result> result1 = purchasedMapper.getOne(id);
        return result1;
    }

    /**
     * @Author mayongfeng
     * @Date 10:17 2021/2/20
     * @Description 通过变更状态查询明细
     *
     **/
    public List getSelectDetail(Integer id,Integer sheetType) {
        List<Result> results = new ArrayList<>();
        /*判断是否是变更的提报计划*/
        if(sheetType==1){
            results = purchasedMapper.getResultPlanList(id);
        }else if(sheetType==2){
            results = purchasedMapper.getResultChangeList(id);
        }
        return results;
    }

    /**
     * @Author mayongfeng
     * @Date 10:17 2021/2/20
     * @Description 通过生产令查询输出表的明细
     *
     **/
    public List<Result> getResultDetail(String prodNo) {
        List<Result> results = purchasedMapper.getResultDetail(prodNo);
        return results;
    }

    /**
     * @Author mayongfeng
     * @Date 8:31 2021/2/22
     * @Description 查询拆分页面的明细详情
     *
     **/
    public List<Result> findPlanListQuery(Result result) {
        List<Result> resultPlanList = purchasedMapper.getResultPlanList(result.getId());
        return resultPlanList;
    }

    /**
     * @Author mayongfeng
     * @Date 8:31 2021/2/22
     * @Description 原始单自动拆分功能
     *
     **/
    public List<Result> findautoSplit(Result result) {
        logService.saveLog("外购件拆分功能", "拆分的主键：" + result.getId());
        /*存放拆分后的list给前端*/
        List<Result> newList = new ArrayList<>();
        Result result3 = null;
        int countMark = 0;//分配标记
        int modifyTag = 0;
        /*通过Id查询计划明细条数*/
        List<Result> resultPlanList = purchasedMapper.getResultPlanListSearch(result);
        /*通过Id查询生产令数量*/
        List<Result> resultProdNum = purchasedMapper.getOneSearch(result);
        /*主表和生产令表的数据*/
        for (Result result1 : resultProdNum) {
            countMark++;
           /*明细表的数据*/
            for (Result result2 : resultPlanList) {
                modifyTag++;
                if(isInteger(result2.getNum()/result1.getProNum())){
                    Double aivNum = ((result2.getNum()/result1.getProNum())*result1.getProdNum());
                    result3 = new Result();
                    result3.setSplitNum(aivNum);
                    copyModel(result3,result1, result2,modifyTag);
                    newList.add(result3);
                }else {
                    result3 = new Result();
                    result3.setSplitNum(0.0);
                    if(countMark==1){
                        result3.setSplitNum(result2.getNum());
                    }
                    copyModel(result3,result1, result2,modifyTag);
                    newList.add(result3);
                }
            }
        }

        return newList;
    }

    /**
     * @Author mayongfeng
     * @Date 8:31 2021/2/22
     * @Description 变更单自动拆分功能
     *
     **/
    public List<Result> autoChaSplit(Result result) {
        logService.saveLog("外购件变更单拆分功能", "拆分的主键：" + result.getId());
        /*存放拆分后的list给前端*/
        List<Result> newList = new ArrayList<>();
        Result result3 = null;
        int countMark = 0;//分配标记
        int modifyTag = 0;
        /*通过Id查询变更表的计划明细条数*/
        List<Result> resultPlanList = purchasedMapper.getResultChangeistSearch(result);
        /*通过Id查询生产令数量*/
        List<Result> resultProdNum = purchasedMapper.getOneSearch(result);
        /*主表和生产令表的数据*/
        for (Result result1 : resultProdNum) {
            countMark++;
            /*明细表的数据*/
            for (Result result2 : resultPlanList) {
                modifyTag++;
                if(isInteger(result2.getAfterNum()/result1.getProNum())){
                    Double aivNum = ((result2.getAfterNum()/result1.getProNum())*result1.getProdNum());
                    result3 = new Result();
                    result3.setSplitNum(aivNum);
                    copychangeModel(result3,result1, result2,modifyTag);
                    newList.add(result3);
                }else {
                    result3 = new Result();
                    result3.setSplitNum(0.0);
                    if(countMark==1){
                        result3.setSplitNum(result2.getAfterNum());
                    }
                    copyModel(result3,result1, result2,modifyTag);
                    newList.add(result3);
                }
            }
        }

        return newList;
    }

    /**
     * @Author mayongfeng
     * @Date 9:33 2021/2/23
     * @Description model的复制转移
     *
     **/
    private void copyModel(Result result3,Result result1, Result result2,Integer modifyTag) {
        /*物理描述*/
        result3.setMalDesc(result2.getMalDesc());
        /*单位*/
        result3.setUnit(result2.getUnit());
        /*型号/标准号*/
        result3.setStandard(result2.getStandard());
        /*品牌*/
        result3.setBrand(result2.getBrand());
        /*备注*/
        result3.setRemark(result2.getRemark());
        /*附件*/
        result3.setUrl(result2.getUrl());
        /*项目名称*/
        result3.setProName(result1.getProName());
        /*生产令*/
        result3.setProdNo(result1.getProdNo());
        /*Id*/
        result3.setSheetId(result1.getId());
        /*planid*/
        result3.setPlanId(result2.getId());
        /*生产令里面的项目数量*/
        result3.setProdNum(result1.getProdNum());

        result3.setModifyTag(modifyTag);
    }

    /**
     * @Author mayongfeng
     * @Date 9:33 2021/2/23
     * @Description model的复制转移
     *
     **/
    private void copychangeModel(Result result3,Result result1, Result result2,Integer modifyTag) {
        /*物理描述*/
        result3.setMalDesc(result2.getAfterMalDesc());
        /*变更原因*/
        result3.setChangeReason(result2.getChangeReason());
        /*单位*/
        result3.setUnit(result2.getAfterUnit());
        /*型号/标准号*/
        result3.setStandard(result2.getAfterStandard());
        /*品牌*/
        result3.setBrand(result2.getAfterBrand());
        /*备注*/
        result3.setRemark(result2.getAfterRemark());
        /*附件*/
        result3.setUrl(result2.getAfterUrl());
        /*项目名称*/
        result3.setProName(result1.getProName());
        /*生产令*/
        result3.setProdNo(result1.getProdNo());
        /*Id*/
        result3.setSheetId(result1.getId());
        /*planid*/
        result3.setPlanId(result2.getId());
        /*生产令里面的项目数量*/
        result3.setProdNum(result1.getProdNum());
        result3.setChangePlanId(result2.getPlanId());
        result3.setModifyTag(modifyTag);
    }

    /**
     * @Author mayongfeng
     * @Date 16:41 2021/2/22
     * @Description 判断double类型是否为整数
     *
     **/
    public static boolean isInteger(double d) {
        if ((int) d == d) { //强制转换du后会丢失精度zhi,如果丢dao失精度的数和原数zhuan相等，说明就是shu整数
            return true;
        } else {
            return false;
        }
    }

    /**
     * @Author mayongfeng
     * @Date 16:31 2021/2/23
     * @Description 验证拆分后的数量和提报的数量是否相同
     **/
    public int isSumNum(List<Result> prodPlaDetList) {
        logService.saveLog("外购件原始单拆分提交", "生产令");
        Map<Integer, Double> map = new HashMap<Integer, Double>();
        for(Result result: prodPlaDetList){
            Integer planId = result.getPlanId();
            if(map.containsKey(planId)){
                map.put(planId,  numberDouble(map.get(planId) , result.getSplitNum()));
            }else{
                map.put(planId, result.getSplitNum());
            }
        }

        /** 循环取map的值*/
        for(Map.Entry<Integer, Double> mapz : map.entrySet()){
            /** 查询原计划单的明细*/
            Result planDatil =  purchasedMapper.getPlanid(mapz.getKey());
            if(!planDatil.getNum().toString().equals(mapz.getValue().toString())){
                return -2;
            }
        }
        /** 添加用的实体类*/
        Result addResult = null;
        Result sheetResult = null;
        Result planResult = null;
        int i= 0;
        int sheetId = 0;
        /** 拆分成功以后存放到提报计划输出表*/
        for (Result result : prodPlaDetList) {
            sheetId = result.getSheetId();
            addResult = new Result();
            sheetResult = new Result();
            planResult = new Result();
            sheetResult = purchasedMapper.getSheetResult(result.getSheetId());
            planResult = purchasedMapper.getplanResult(result.getPlanId());
            copy(sheetResult,addResult);
            copy(planResult,addResult);
            addResult.setProdNo(result.getProdNo());
            addResult.setSplitNum(result.getSplitNum());
            addResult.setLssueStatus(1);
            addResult.setProNum(result.getProdNum());
            addResult.setExtendUrl(planResult.getUrl());
            addResult.setSpecial(sheetResult.getMalType());
            if(addResult.getSheetType()==1){
                addResult.setChangeMark(0);
            }else if(addResult.getSheetType()==2){
                addResult.setChangeMark(1);
            }
             i = purchasedMapper.addResult(addResult);

        }
        purchasedMapper.updateSheetId(sheetId);

        return i;
    }

    /**
     * @Author mayongfeng
     * @Date 16:31 2021/2/23
     * @Description 验证变更拆分后的数量和提报的数量是否相同
     **/
    public int isSumChaNum(List<Result> prodChaDetList) {
        logService.saveLog("外购件变更单拆分提交", "生产令");
        Map<Integer, Double> map = new HashMap<Integer, Double>();
        for(Result result: prodChaDetList){
            /** 变更的时候planId是chang表里面的Id*/
            Integer planId = result.getPlanId();
            if(map.containsKey(planId)){
                map.put(planId,  numberDouble(map.get(planId) , result.getSplitNum()));
            }else{
                map.put(planId, result.getSplitNum());
            }
        }

        /** 循环取map的值*/
        for(Map.Entry<Integer, Double> mapz : map.entrySet()){
            /** 查询变更单计划单的明细*/
            Result changeDatil =  purchasedMapper.getChangeid(mapz.getKey());
            if(!changeDatil.getAfterNum().toString().equals(mapz.getValue().toString())){
                return -2;
            }
        }
        /** 添加用的实体类*/
        Result addResult = null;
        Result sheetResult = null;
        Result changeResult = null;
        int i= 0;
        int sheetId = 0;
        /** 拆分成功以后存放到提报计划输出表*/
        for (Result result : prodChaDetList) {
            sheetId = result.getSheetId();
            addResult = new Result();
            sheetResult = new Result();
            changeResult = new Result();
            sheetResult = purchasedMapper.getSheetResult(result.getSheetId());
            changeResult = purchasedMapper.getChangeid(result.getPlanId());
            copy(sheetResult,addResult);
            copy(changeResult,addResult);
            addResult.setProdNo(result.getProdNo());
            addResult.setSplitNum(result.getSplitNum());
            addResult.setProNum(result.getProdNum());
            addResult.setExtendUrl(changeResult.getAfterUrl());
            addResult.setSpecial(sheetResult.getMalType());
            if(addResult.getSheetType()==1){
                addResult.setChangeMark(0);
            }else if(addResult.getSheetType()==2){
                addResult.setChangeMark(1);
            }
            i = purchasedMapper.updateResult(addResult);

        }
        purchasedMapper.updateSheetId(sheetId);

        return i;
    }

    /**
     * @Author mayongfeng
     * @Date 10:09 2021/2/20
     * @Description 在输出表更改拆分后的数据的状态
     *
     **/
    public int modifyLssue(Integer resultAndSheetId,String prodNo) {
        logService.saveLog("外购件拆分多个生产令拆分后的下达", "生产令"+prodNo);
        return purchasedMapper.modifyLssue(prodNo);
    }

    /**
     * @Author mayongfeng
     * @Date 13:41 2021/3/3
     * @Description 将主表的数据添加到输出表并且修改下达状态
     *
     **/
    public int addResultAndModifyLssue(Integer resultAndSheetId) {
        logService.saveLog("外购件一个生产令的下达", "主键"+resultAndSheetId);
        /*通过主表Id查询主表信息关联生产令表*/
        List<Result> result = purchasedMapper.getOne(resultAndSheetId);
        /*通过主表Id查询原始单明细表的集合*/
        List<Result> planList = purchasedMapper.getResultPlanList(resultAndSheetId);
        int i = 0;
        /*循环添加到输出表里面的数据*/
        for (Result result1 : planList) {
            result1.setPlanId(result1.getId());
            result1.setSheetId(result.get(0).getId());
            result1.setProCode(result.get(0).getProCode());
            result1.setProName(result.get(0).getProName());
            result1.setProNum(result.get(0).getProdNum());
            result1.setProUnit(result.get(0).getProUnit());
            result1.setMalType(result.get(0).getMalType());
            result1.setPart(result.get(0).getPart());
            /** 外购件状态*/
            result1.setReportType(result.get(0).getReportType());
            result1.setPostName(result.get(0).getPostName());
            result1.setPostTel(result.get(0).getPostTel());
            result1.setPostDept(result.get(0).getPostDept());
            /** 变更标识 0=未变更，1=已变更*/
            result1.setChangeMark(0);
            /** 状态 0=删除，1=正常 */
            result1.setStatus(1);
            result1.setSpecial(result.get(0).getSpecial());
            result1.setReviewer(result.get(0).getReviewer());
            result1.setVerifier(result.get(0).getVerifier());
            result1.setBranchName(result.get(0).getBranchName());
            /** 下发状态：1=未下发，2=已下发*/
            result1.setLssueStatus(2);
            result1.setSplitNum(result1.getNum());
            result1.setLssueTime(new Date());
            result1.setProdNo(result.get(0).getProdNo());
            i = purchasedMapper.addResult(result1);

        }
        i = purchasedMapper.updateChaSheetId(resultAndSheetId);
        return i;

    }


/********************************************工具方法*******************************************************************/
    /**
     * 复制对象，并排除空值属性
     *
     * @param source 源对象
     * @param target 目标对象
     */
    public static void copy(Object source, Object target) {
        BeanUtils.copyProperties(source, target, getNullPropertyNames(source));
    }
    /**
     * @Author mayongfeng
     * @Date 11:04 2021/3/5
     * @Description double类型的数据进行转换在做运算
     *
     **/
    public static Double numberDouble(Double a,Double b) {
        DecimalFormat df = new DecimalFormat("0.0");
        BigDecimal b1 = new BigDecimal(df.format(a));
        BigDecimal b2 = new BigDecimal(df.format(b));
        return b1.add(b2).doubleValue();
    }


    public List<Result> getChangeById(Integer id) {
        List<Result> results = purchasedMapper.getResultChangeList(id);
        return results;
    }

    /** 主表变更数据下达并且修改到输出表*/
    public int chaSheetRelease(Result result) {
        int i=0;
        /** 判断被变更的主单数据是否是下达*/
        if(result.getSheetId()!=null || "".equals(result.getSheetId())){
            /** 通过变更主单的sheetId查询被变更的主单下达状态*/
            Result sheetResult = purchasedMapper.getSheetResult(result.getSheetId());
            /** 判断被变更的数据是否下达1=未下达,2=已下达*/
            if(sheetResult.getLssueStatus()==1){
                return -2;
            }else if(sheetResult.getLssueStatus()==2){
                List<Result> resultList = purchasedMapper.getResultChangeList(result.getId());
                for (Result result1 : resultList) {
                     i = purchasedMapper.updatePlandId(result1);

                }
                i = purchasedMapper.updateChaSheetId(result.getId());
            }
        }
        return i;
    }

    public int getSheetResult(Integer sheetId) {
        int i =0;
       Result result = purchasedMapper.getSheetResult(sheetId);
       if(result.getRawSplit()==0){
            i=-1;
       }else if(result.getRawSplit()==1){
           i=1;
        }
        return i;
    }
}

